package com.hy.myapp.action;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.hy.myapp.Entity.User;
import com.hy.myapp.service.UserService;

@Controller
public class UserCtrl {
	private final static Logger logger = LoggerFactory.getLogger(UserCtrl.class);
	
	@Autowired
	private UserService userService;
	
	@PostMapping(value="/user/Register")
	public ModelAndView register(String uname,String pswd,String repswd,String email) {
		ModelAndView mav=new ModelAndView("user/register");
		
		boolean isNameUnique=userService.isUniqueName(uname);
		if(!isNameUnique) {
			mav.addObject("errMsg", "用户名：'"+uname+"'已经存在了。");
			return mav;
		}
		
		boolean isEmailUnique=userService.isUniqueEmail(email);
		if(!isEmailUnique) {
			mav.addObject("errMsg", "邮件地址：'"+email+"'已经存在了。");
			return mav;
		}
		
		boolean added=userService.addOneUser2Db(uname, repswd, email);
		
		if(added) {
			logger.info("User:{} added.",uname);
			return new ModelAndView("redirect:/login");
		}else {
			return new ModelAndView("error");
		}
	}
	
	@PostMapping(value="/user/Login")
	public ModelAndView login(String uname,String pswd,HttpSession httpSession) {
		User user=userService.searchUserByNamePswd(uname, pswd);
		
		if(user!=null) {
			httpSession.setAttribute("user", user);
			logger.info("Now User:{} logged in.",user.getName());
			return new ModelAndView("redirect:/reputation/gotoRptnList");
		}else {
			ModelAndView mav=new ModelAndView("login");
			mav.addObject("errMsg", "用户名或密码有误.");
			return mav;
		}
	}
	
	@RequestMapping(value = "/user/Logout",method = RequestMethod.GET)
    public ModelAndView logout(HttpSession httpSession){
		httpSession.invalidate();
		ModelAndView mav=new ModelAndView("redirect:/");
		mav.addObject("errMsg", "您已安全登出系统.");
		return mav;
    }
}
